package com.kaoshi.myweb.webtest.interview.code;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeSet;
import java.util.Map.Entry;

public class SortMap {
	public static void main(String[] args) throws Exception {
		
		FileInputStream fis = new FileInputStream("user.txt");
		BufferedReader bReader = new BufferedReader(new InputStreamReader(fis));
		String userString;
		HashMap<String, User> map = new HashMap<String, SortMap.User>();
		
		while ((userString = bReader.readLine()) != null) {
			User user = User.setUser(userString);
			User oUser = map.get(user.name) ;
			if(oUser != null)
				oUser.count += 1;
			else {
				user.count = 1;
				map.put(user.name, user);
			}
		}
		
		User.sortMap(map);
	}
	
	
	static class User{
		
		private String name;
		private int age;
		private int count;
		
		public static User setUser(String userString) {
			String[] uStrings = userString.split(",");
			User user = new User();
			user.name = uStrings[0];
			user.age = Integer.parseInt( uStrings[1]);
			
			return user;
		}
		
		public static void sortMap(HashMap<String, User> map) {
			TreeSet<User> users = new TreeSet<SortMap.User>(new Comparator<User>() {

				@Override
				public int compare(User o1, User o2) {
					if(o1.count < o2.count){
						return -1;
					}else if (o1.count > o2.count) {
						return 1;
					}else {
						return o1.name.compareTo(o2.name);
					}
				}
				
			});
			
			for (Entry<String, User> user : map.entrySet()) {
				users.add(user.getValue());
			}
			
			Iterator<User> iterator = users.iterator();
			while (iterator.hasNext()) {
				SortMap.User user = (SortMap.User) iterator.next();
				System.out.println(user.name + ":" + user.count);
			}
		}
	}
}
